package com.gensdai.leliang.retrofitUtils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;

import com.gensdai.leliang.entity.parseBean.BaseParse;


import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;


/**   baseObserver封装  内部进度条一些解注册方法
 * Created by LT on 2017/6/8.
 */

public abstract class BaseObserver<T> implements Observer<BaseParse<T>> {
    private Context mContext;
    private ProgressDialog mDialog;
    private Disposable mDisposable;
    private final int SUCCESS_CODE = -1;

    public BaseObserver(Context mContext) {
        this.mContext = mContext;
    }

    public BaseObserver(Context mContext,ProgressDialog dialog) {
        this.mContext = mContext;
        this.mDialog = dialog;

        //监听dialog动作
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                /*当用户取消dialog 断开监听*/
                mDisposable.dispose();
            }
        });
    }

    //暴露给调用者用于关闭 观察
    public Disposable getDisposable(){
        return mDisposable;
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        mDisposable = d;
    }

    @Override
    public void onNext(@NonNull BaseParse<T> valus) {
        if(valus.success){
            T t = valus.data;
            onHandleSuccess(t);
            onHandleMessageSuccess(t,valus.message);
        }else{
            onHandleError(valus.code,valus.message);
        }
    }



    @Override
    public void onError(@NonNull Throwable e) {
        if(mDialog != null && mDialog.isShowing()){
            mDialog.dismiss();
        }
        e.printStackTrace();

        onFailure(e);
    }

    @Override
    public void onComplete() {
        Log.d("onComplete", "onComplete");

        if(mDialog != null && mDialog.isShowing()){
            mDialog.dismiss();
        }
        onRequestEnd();
    }

    //跟服务器的连接失败，请具体查看e跑出来的异常
    public void onFailure(Throwable e){
        e.printStackTrace();
        Log.d("onFailure", "onFailure" + "出现这个代表与服务器连接失败具体请查找是服务器端出错还是本地");
        onRequestEnd();
    };

    //整条请求结束
    public void onRequestEnd(){
        Log.d("onRequestEnd", "onRequestEnd");
    }
    public void onHandleMessageSuccess(T t,String message){

    }

    //服务器返回的正确数据
    public abstract void onHandleSuccess(T t);

    //服务器返回的code跟异常处理
    public  abstract void onHandleError(int code, String message);
}
